#coding:utf8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from review.mysqlhandler import dbh
import datetime

#
#=============================================MENU===========================================
#
def index(request):
	username = request.session['user']
	if username == 'admin':			
		today = datetime.datetime.now().strftime('%Y-%m-%d')
		adm = Admin(today)
		menulist = adm.retMenu()
		fllist = adm.retFL()
		data = {
			'today':today,
			'menulist':menulist,
			'fllist':fllist,
			'username':username
		}
		return render_to_response('admin.html',data)
	else:
		flag = False
		data = {
			'flag':flag,
		}
		return render_to_response('login.html',data)


def login(request):
	user = request.GET.get('user',None)
	passwd = request.GET.get('passwd',None)

	flag = False
	if user == 'admin' and passwd == 'admin!@#':
		flag = True

	request.session['user']=user
	data = {
		'flag':flag,
	}
	return render_to_response('login.html',data)


def test_cache():
    from bae.api.memcache import BaeMemcache

    ### 创建一个cache
    cache = BaeMemcache()

    body = []
    ### 存放一个user，value对
    if cache.set('user', 'admin'):
        body.append("set user => value success!")

    ### 获取user对应的value
    body.append("get %s success!"%cache.get('user'))
    return body

def cpmc(request):
	flmc = request.GET.get('flmc',None)
	msg = ''
	sqlcpmc= '''
			SELECT CPMC FROM T_CP
			WHERE FL_ID = (
				SELECT FL_ID FROM T_FL
				WHERE FLMC = '%s')
			ORDER BY CPMC;
		''' % flmc
	cpmclist = dbh.ExecQuery(sqlcpmc)
	cpmchtml = '''
			<li onmousedown="getValue('i_input_cpmc',this.innerText);hideListDiv('listcpmc');">
			%s
			</li>
	'''
	for cpmc in cpmclist:
		msg += cpmchtml % cpmc
	return HttpResponse('<ul id="i_ul_cpmc">' + msg + '</ul>')

# 
# 为今日菜谱加菜
# 
def addTodayCP(request):
	menudata = request.GET.get('data',None)
	cpmc = request.GET.get('cpmc',None)
	msg = '' # 给前端的返回提示内容
	try:
		# 通过菜品名称返回菜品ID
		cpid = dbh.ExecQuery("SELECT CP_ID FROM T_CP WHERE CPMC = '%s'" % cpmc)[0][0]

		newid = None # 新增菜单的编号
		rev = Admin(menudata)
		maxid = rev.retMaxID()[0][0] # 评论编号后3位尾号
		if maxid:
			newid = datetime.datetime.now().strftime('%Y%m%d') + str(int(maxid)+1).zfill(3)
		else:
			newid = datetime.datetime.now().strftime('%Y%m%d') + '001'

		if newid:
			sqlAddCP = '''
				INSERT INTO T_MENU VALUES('%s','%s','%s');
			''' % (newid,menudata,cpid)
			dbh.ExecNonQuery(sqlAddCP)
			msg = 'complete'
	except:
		msg = '保存失败,可以再试一次!'

	return HttpResponse(msg)


#
#=============================================FL===========================================
#
def fl(request):
	username = request.session['user']
	if username == 'admin':
		adm = Admin(None)
		data = {
			'fllist':adm.retFL(),
		}
		return render_to_response('fl.html',data)
	else:
		flag = False
		data = {
			'flag':flag,
		}
		return render_to_response('login.html',data)


#
#=============================================CP===========================================
#
def cp(request,offset=None):# offset=None表示当输入的地址为/cp/的时候，没带2位flid情况下默认为为/CP/00/
	username = request.session['user']
	if username == 'admin':
		adm = Admin(None)
		if offset == '00' or offset == None:
			cplist = adm.retCP()
		else:
			cplist = adm.retFLCP(offset)

		data = {
			'fllist':adm.retFL(),
			'curflid':offset,
			'cplist':cplist,
		}
		return render_to_response('cp.html',data)
	else:
		flag = False
		data = {
			'flag':flag,
		}
		return render_to_response('login.html',data)

def addCP(request):
	msg = '' # 给前端的返回提示内容
	cpid = request.GET.get('cpid',None)
	cpmc = request.GET.get('cpmc',None)
	flid = request.GET.get('flid',None)
	try:
		if cpid and cpmc and flid:
			sqlAddCP = '''
				INSERT INTO T_CP VALUES('%s','%s','%s');
			''' % (cpid,cpmc,flid)
			dbh.ExecNonQuery(sqlAddCP)
			msg = 'complete'
	except:
		msg = '新增失败,可以再试一次!'
	return HttpResponse(msg)

def updateCP(request):
	msg = '' # 给前端的返回提示内容
	cpid = request.GET.get('cpid',None)
	cpmc = request.GET.get('cpmc',None)
	try:
		if cpid and cpmc:
			sqlUpdateCP = '''
				UPDATE T_CP SET CPMC='%s' WHERE CP_ID='%s';
			''' % (cpmc,cpid)
			dbh.ExecNonQuery(sqlUpdateCP)
			msg = 'complete'
	except:
		msg = '更新失败,可以再试一次!'
	return HttpResponse(msg)

class Admin(object):
	"""docstring for Admin"""
	def __init__(self, dataNow):
		self.dataNow = dataNow

	def retMenu(self):
		sqlMenu = '''
			SELECT A.MENU_ID,C.FLMC,B.CPMC FROM T_MENU A
			LEFT JOIN T_CP B ON A.CP_ID = B.CP_ID
			LEFT JOIN T_FL C ON B.FL_ID = C.FL_ID
			WHERE A.RQ = '%s'
			ORDER BY A.CP_ID;
		''' % self.dataNow
		return dbh.ExecQuery(sqlMenu)
	
	#
	# 返回所有分类
	#
	def retFL(self):
		sqlFL = '''
			SELECT FLMC,FL_ID FROM T_FL
			ORDER BY FL_ID;
		'''
		return dbh.ExecQuery(sqlFL)

	# 
	# 返回当天菜单最后一道菜的编号末3位，如果当天对该菜品无评论则返回None
	# 
	def retMaxID(self):
		sqlMaxID = '''
			SELECT RIGHT(MAX(MENU_ID),3) FROM T_MENU
			WHERE DATE_FORMAT(RQ,'%%Y-%%m-%%d') = '%s';
		''' % self.dataNow
		return dbh.ExecQuery(sqlMaxID)

	#
	# 返回所有菜品
	#
	def retCP(self):
		sqlCP = '''
			SELECT CP_ID,CPMC FROM T_CP
			ORDER BY CP_ID;
		'''
		return dbh.ExecQuery(sqlCP)

	#
	# 按分类返回菜品
	#
	def retFLCP(self,flid):
		sqlFLCP = '''
			SELECT CP_ID,CPMC FROM T_CP
			WHERE FL_ID='%s'
			ORDER BY CP_ID DESC;
		''' % flid # 当按菜类查询时按照cpid倒序排列，这样就能第一时间看到刚添加的菜品，也好查看最后一个id号为新增ID编号是多少带来便利
		return dbh.ExecQuery(sqlFLCP)